package com.sfc.sdsr.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipUtil {
	public static byte[] compress(byte[] bytes){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try{
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(bytes);
            gzipOutputStream.close();
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return byteArrayOutputStream.toByteArray();
    }
	
	public static byte[] decompress(byte[] contentBytes){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
        	GZIPInputStream gzis = new GZIPInputStream(new ByteArrayInputStream(contentBytes));
        	byte[] bytes = new byte[1024];
        	int read = 0;
        	while ((read = gzis.read(bytes)) != -1) {
        		out.write(bytes,0,read);
        	}
        	
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return out.toByteArray();
    }

    /**
     * DEBUGGING FUNCTION
     * returns the bytes as a single spaces dividing bytes string
     */
    public static String debugByteArray(byte[] bytes) {
        StringBuffer sBuffer = new StringBuffer();
        for (byte b : bytes) {
            sBuffer.append(String.format("%02x ", b));
        }
        return sBuffer.toString();
    }
}
